package com.one.blocks.security.authc.smscode;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href="mailto:idler41@163.con">linfuxin</a> created on 2023-08-27 10:51:28
 */
public class SmsCodeAuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter {

    public final String FORM_MOBILE_KEY;
    public final String FORM_SMS_CODE_KEY;

    public SmsCodeAuthenticationProcessingFilter(
            String url, String mobileKey, String smsCodeKey,
            AuthenticationManager authenticationManager, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) {
        super(new AntPathRequestMatcher(url, HttpMethod.POST.name()));
        this.FORM_MOBILE_KEY = mobileKey;
        this.FORM_SMS_CODE_KEY = smsCodeKey;
        setAuthenticationManager(authenticationManager);
        setAuthenticationSuccessHandler(successHandler);
        setAuthenticationFailureHandler(failureHandler);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String mobile = obtainMobile(request);
        mobile = mobile != null ? mobile.trim() : StringUtils.EMPTY;
        String smsCode = obtainSmsCode(request);
        smsCode = smsCode != null ? smsCode.trim() : StringUtils.EMPTY;
        return getAuthenticationManager().authenticate(new SmsCodeAuthenticationToken(mobile, smsCode));
    }

    private String obtainMobile(HttpServletRequest request) {
        return request.getParameter(FORM_MOBILE_KEY);
    }

    private String obtainSmsCode(HttpServletRequest request) {
        return request.getParameter(FORM_SMS_CODE_KEY);
    }
}
